package ca.kooki.codesnippet.core;

import java.io.File;
import java.io.IOException;

public class FileAccessor {

  //```````````````````````
  // STATIC VARIABLES
  //```````````````````````

  private static final int MAX_SLEEP_TIME = 1000;
  private static final int ONE_MINUTE_AGO_IN_MILLISECONDS = 60*1000;
  
  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````

  private static String _filename;

  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````

  public FileAccessor(String filename)
  {
    init(filename);
  }
  
  private void init(String filename)
  {
    _filename = filename;
  }

  //```````````````````````
  // INTERFACE
  //```````````````````````
  
  public boolean lock() throws IOException, InterruptedException
  {
    File lockedFile = new File(_filename + ".lock");

    for (int i=0; i<10; i++)
    {
      if (!lockedFile.exists())
      {
        lockedFile.createNewFile();
        lockedFile.setLastModified(SystemDate.Now().getTime());
        return true;
      }
      else
      {
        long lastModified = lockedFile.lastModified();
        long oneMinuteAgo = SystemDate.Now().getTime() - ONE_MINUTE_AGO_IN_MILLISECONDS;
        if (oneMinuteAgo > lastModified)
        {
          lockedFile.delete();
        }
      }
      int currentSleepTime = (int)(Math.random()*MAX_SLEEP_TIME);
      Thread.sleep(currentSleepTime);
    }
    return false;
  }
  
  public boolean unlock()
  {
    File lockedFile = new File(_filename + ".lock");
    lockedFile.delete();
    return true;
  }
  
}
